const _ = require("lodash");
const moment = require("moment");
const router = require("koa-router")();
const prettyBytes = require("pretty-file-bytes");

/**
 * api {get} /home/app/statistics 统计
 *
 */
router.get("/statistics", async (ctx, nex) => {
  const time = moment().format("YYYY-MM-DD");
  const user = ctx.user;
  // 查询该用户名下的应用id
  const baas = ctx.baas;
  // 查询应用所用统计
  const { days = 30 } = ctx.query;
  const monthLog = await BaaS.Models.statistics
    .query(qb => {
      qb.where("baas_id", "=", baas.id);
      qb.orderBy("id", "desc");
      qb.where(
        "created_at",
        ">",
        `${moment()
          .subtract(1, "months")
          .format("YYYY-MM-DD")}`
      );
    })
    .fetchAll();
  const allLog = {};
  let allRequest = 0;
  let allFlow = 0;
  let allStorage = 0;
  let allDebug = 0;
  // 统计流量和内存
  for (const log of monthLog) {
    allRequest += log.request_num;
    allDebug += log.debug;
    allFlow += ctx.format(log.flow);
  }
  if (monthLog.length) {
    allStorage += ctx.format(monthLog[0].storage);
  } else {
    allStorage = 0;
  }

  allFlow = prettyBytes(allFlow);
  allStorage = prettyBytes(allStorage);
  Object.assign(
    allLog,
    { request: allRequest },
    { flow: allFlow },
    { storage: allStorage },
    { debug: allDebug }
  );
  // 组装七日内请求折线图数据
  const requests = [];
  const storages = [];
  const flows = [];
  const debugs = [];
  const dates = [];

  // 组装日期
  for (let i = days; i >= 1; i--) {
    dates.push(
      moment()
        .subtract(i, "days")
        .format("YYYY-MM-DD")
    );
  }

  const months = await BaaS.Models.statistics
    .query(qb => {
      qb.where("baas_id", "=", baas.id);
      qb.where(
        "date",
        ">",
        `${moment()
          .subtract(1, "months")
          .format("YYYY-MM-DD")}`
      );
    })
    .fetchAll();
  // 查询对应日期下的内存，请求等
  for (const key in dates) {
    let has = false;
    for (const k in months) {
      if (dates[key] == moment(months[k].date).format("YYYY-MM-DD")) {
        // 把内存和流量转换成KB;
        storages.push(ctx.format(months[k].storage));
        flows.push(ctx.format(months[k].flow));
        requests.push(months[k].request_num);
        debugs.push(months[k].debug);
        has = true;
      }
    }
    if (!has) {
      requests.push(0);
      storages.push(0);
      flows.push(0);
      debugs.push(0);
    }
  }
  const maxStorage = _.max(storages);
  const storage = prettyBytes(maxStorage);
  const storageUnit = storage.split(" ")[1];
  for (const key in storages) {
    const prettyStorage = prettyBytes(storages[key], storageUnit);
    storages[key] =
      Math.ceil(parseFloat(prettyStorage) * Math.pow(10, 4)) / Math.pow(10, 4);
  }
  const maxFlow = _.max(flows);
  const flow = prettyBytes(maxFlow);
  const flowUnit = flow.split(" ")[1];
  for (const key in flows) {
    const prettyFlows = prettyBytes(flows[key], flowUnit);
    flows[key] =
      Math.ceil(parseFloat(prettyFlows) * Math.pow(10, 4)) / Math.pow(10, 4);
  }
  ctx.success({
    allLog,
    requests,
    storages,
    storageUnit,
    flows,
    flowUnit,
    debugs,
    dates
  });
});
module.exports = router;
